<template>
  <section>
    <!--工具条 - 高级查询框-->
    <el-col :span="24" class="toolbar" style="padding-bottom: 0px;">
      <el-form :inline="true" :model="query">
        <el-form-item>
          <el-input v-model="query.keyword" placeholder="请输入关键字"></el-input>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" v-on:click="search">查询</el-button>
        </el-form-item>
      </el-form>
    </el-col>

    <!--列表-->
    <el-table :data="pageInfo.rows"
              highlight-current-row v-loading="listLoading"
              @selection-change="selsChange"
              style="width: 100%;"
              height="550"
    >
      <el-table-column type="selection" width="55">
      </el-table-column>
      <el-table-column type="index" width="60">
      </el-table-column>
      <el-table-column prop="title" label="名称" width="120" sortable>
      </el-table-column>
      <el-table-column prop="cover" label="封面图" width="120" sortable>
        <template v-slot="scope">
          <img :src="imageUrl+''+scope.row.cover" width="100px" height="80px">
        </template>
      </el-table-column>
      <el-table-column prop="saleprice" label="原价" width="100" sortable>
      </el-table-column>
      <el-table-column prop="costprice" label="折扣价" width="100" sortable>
      </el-table-column>
      <el-table-column prop="isnew" label="是否新车" width="120" sortable>
        <template v-slot="scope">
          <span v-if="scope.row.isnew == 1">是</span>
          <span v-else>否</span>
        </template>
      </el-table-column>
      <el-table-column prop="reigstertime" label="上牌时间" width="100" sortable>
      </el-table-column>
      <el-table-column prop="mileage" label="里程数" width="100" sortable>
      </el-table-column>
      <el-table-column prop="shopname" label="店铺名称" width="100" sortable>
      </el-table-column>
      <el-table-column prop="onsaletime" label="上架时间" width="100" sortable>
      </el-table-column>
      <el-table-column prop="offsaletime" label="下架时间" width="100" sortable>
      </el-table-column>
      <el-table-column prop="state" label="状态" min-width="180" sortable>
        <template v-slot="scope">
          <span v-if="scope.row.state == 1" style="color: blue">上架</span>
          <span v-else>下架</span>
        </template>
      </el-table-column>
      <el-table-column prop="costeffective" label="超值" min-width="180" sortable>
        <template v-slot="scope">
          <span v-if="scope.row.costeffective == 1">是</span>
          <span v-else>否</span>
        </template>
      </el-table-column>
      <el-table-column prop="rushsale" label="急售" min-width="180" sortable>
        <template v-slot="scope">
          <span v-if="scope.row.rushsale == 1">是</span>
          <span v-else>否</span>
        </template>
      </el-table-column>
      <el-table-column prop="quasinewcar" label="准新车" min-width="180" sortable>
        <template v-slot="scope">
          <span v-if="scope.row.quasinewcar == 1">是</span>
          <span v-else>否</span>
        </template>
      </el-table-column>
      <el-table-column prop="transitivecountry" label="可提全国" min-width="180" sortable>
        <template v-slot="scope">
          <span v-if="scope.row.transitivecountry == 1">是</span>
          <span v-else>否</span>
        </template>
      </el-table-column>
      <el-table-column prop="type.name" label="类型" width="100" sortable>
      </el-table-column>
      <el-table-column prop="seller.nickname" label="营销人员" width="100" sortable>
      </el-table-column>
      <el-table-column prop="auditstate" label="审核状态" width="100" sortable>
        <template v-slot="scope">
          <span v-if="scope.row.auditstate == 1">已审核</span>
          <span v-else>未审核</span>
        </template>
      </el-table-column>
      <el-table-column label="操作" width="250" fixed="right">
        <template v-slot="scope">
          <el-button size="small" @click="handleEdit(scope.$index, scope.row)">审核</el-button>
          <el-button type="danger" size="small"  @click="handleDel(scope.$index, scope.row)">删除</el-button>
          <el-button size="small" @click="handleResource(scope.$index, scope.row)">资源预览</el-button>
        </template>
      </el-table-column>
    </el-table>

    <!--工具条 - 批量删除&分页条-->
    <el-col :span="24" class="toolbar">
      <el-button type="danger" @click="batchRemove" :disabled="this.sels.length===0">批量删除</el-button>
      <el-pagination
          layout="prev, pager, next"
          :current-page="query.currentPage"
          @current-change="handleCurrentChange"
          :page-size="query.pageSize"
          :total="pageInfo.total"
          style="float:right;">
      </el-pagination>
    </el-col>

    <!--新增界面-->
    <el-dialog title="审核" :visible.sync="carFormVisible" :close-on-click-modal="false">
      <el-form :model="carForm" label-width="80px" :rules="carFormRules" ref="carForm">
        <el-form-item label="标题" prop="title">
          <el-input v-model="carForm.title" :disabled="true" auto-complete="off"></el-input>
        </el-form-item>
        <el-row>
          <el-col :span="12">
            <el-form-item label="原价" prop="saleprice">
              <el-input v-model="carForm.saleprice" :disabled="true" auto-complete="off"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="售价" prop="costprice">
              <el-input v-model="carForm.costprice" :disabled="true" auto-complete="off"></el-input>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="里程" prop="mileage">
              <el-input v-model="carForm.mileage" :disabled="true" auto-complete="off"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="上牌时间" prop="reigstertime">
              <el-date-picker
                  v-model="carForm.reigstertime"
                  type="date"
                  value-format="yyyy-MM-dd"
                  format="yyyy-MM-dd"
                  placeholder="选择日期"
                  :disabled="true">
              </el-date-picker>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="24">
            <el-form-item label="车辆类型" prop="carType">
              <el-cascader
                  placeholder="搜索车辆类型"
                  v-model="carForm.typeId"
                  :options="carTypes"
                  :props="props"
                  filterable
                  style="width: 50%"
              >
              </el-cascader>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="24">
            <el-form-item label="可选项" prop="choose">
                <el-checkbox-group v-model="checkbox" size="medium" >
                  <el-checkbox-button v-for="state in allStates" :label="state" :key="state">{{state}}</el-checkbox-button>
                </el-checkbox-group>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="24">
            <el-form-item label="详细说明" prop="info">
              <quill-editor v-model="carForm.carDetail.info" :disabled="true" :options="quillOptions">
              </quill-editor>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="状态" prop="state">
              <el-select v-model="carForm.auditstate"
                         style="width: 250px"
                         clearable placeholder="请选择"
              >
                <el-option
                    v-for="item in carState"
                    :key="item.codeValue"
                    :label="item.codeIntro"
                    :value="item.codeValue">
                  <span style="float: left">{{ item.codeValue }}</span>
                  <span style="float: right; color: #8492a6; font-size: 13px">{{ item.codeIntro }}</span>
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-form-item label="备注" prop="node">
            <el-input v-model="carForm.node" auto-complete="off"></el-input>
          </el-form-item>
        </el-row>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click.native="carFormVisible = false">取消</el-button>
        <el-button type="primary" @click.native="save" :loading="carFormLoading">提交</el-button>
      </div>
    </el-dialog>

    <!--资源维护-->
    <!--新增界面-->
    <el-dialog title="资源维护" :visible.sync="resourceVisible" :close-on-click-modal="false">
      <el-form :model="carResource" label-width="80px">
        <el-form-item label="主图" prop="image">
          <el-upload
              :disabled="true"
              class="upload-demo"
              :action= "backend"
              :headers="headers"
              :on-remove="handleImgRemove"
              :on-success="handleImgSuccess"
              :file-list="imgFileList"
              list-type="picture">
            <el-button size="small" type="primary">点击上传</el-button>
            <div slot="tip" class="el-upload__tip">只能上传jpg/png文件，且不超过500kb</div>
          </el-upload>
        </el-form-item>
        <el-form-item label="副图" prop="image">
          <el-upload
              :disabled="true"
              class="upload-demo"
              :action= "backend"
              :headers="headers"
              :on-remove="handleViceImgRemove"
              :on-success="handleViceSuccess"
              :file-list="viceImgFileList"
              list-type="picture">
            <el-button size="small" type="primary">点击上传</el-button>
            <div slot="tip" class="el-upload__tip">只能上传jpg/png文件，且不超过500kb</div>
          </el-upload>
        </el-form-item>
        <el-form-item label="更多图集" prop="image">
          <el-upload
              :disabled="true"
              class="upload-demo"
              :action= "backend"
              :headers="headers"
              :on-remove="handleMoreImgRemove"
              :on-success="handleMoreSuccess"
              :file-list="moreImgFileList"
              list-type="picture">
            <el-button size="small" type="primary">点击上传</el-button>
            <div slot="tip" class="el-upload__tip">只能上传jpg/png文件，且不超过500kb</div>
          </el-upload>
        </el-form-item>
      </el-form>
    </el-dialog>
  </section>
</template>

<script>
import { quillEditor } from "vue-quill-editor"
import 'quill/dist/quill.core.css'
import 'quill/dist/quill.snow.css'
import 'quill/dist/quill.bubble.css'
import quillConfig from "../../common/js/quill-config";

export default {
  components:{
    quillEditor
  },
  data() {
    return {
      carState:[
        {codeValue:0,codeIntro:"驳回"},
        {codeValue:1,codeIntro:"通过审核"},
      ],
      resourceVisible:false,
      // 注入
      carResource:{
        viceimg:"",
        moreimg:"",
        img:"",
        carId:"",
      },
      backend:this.backend+"/fastDfs/upload",
      quillOptions:quillConfig,
      imageUrl:this.imageUrl,
      props:{
        label:"name",
        emitPath:false,
        value:"id",
        checkStrictly: true,
        children:'children'
      },
      allStates:["超值","新车","准新车","可迁全国","急售"],
      checkbox:[],
      carTypes:[],
      fileList:[],
      headers:{
        token:localStorage.getItem("token")
      },
      query:{
        currentPage:1,  // 当前页
        pageSize:10,  // 每页显示条数
        keyword:""  // 关键字
      },
      pageInfo:{
        total:0,
        rows:[]
      },
      listLoading: false,
      sels: [],//列表选中列

      carFormVisible: false,//新增修改界面是否显示
      carFormLoading: false,
      carFormRules: {
        name: [
          { required: true, message: '请输入姓名', trigger: 'blur' }
        ]
      },
      employees:[],
      deptTree:[],  // 部门树
      //新增修改界面数据
      carForm: {
        id:"",
        title:"",
        cover:"",
        saleprice:"",
        costprice:"",
        isnew:"",
        reigstertime:"",
        mileage:"",
        shop_id:"",
        shopname:"",
        createtime:"",
        manager:{
          id:""
        },
        parent:{
          id:""
        },
        path:"",
        state:"",
        carDetail:{
          info:"",
        },
        auditstate:"",
        node:""
      },
      imgFileList:[],
      viceImgFileList:[],
      moreImgFileList:[]
    }
  },
  methods: {
    handleAudit(){

    },
    handleResource(index,row){
      this.resourceVisible = true;
      this.carResource.carId = row.id;
      this.getCarResourceByCarId(index,row)
    },
    /**
     * 设置选项
     * @param index
     * @param row
     */
    setCheckbox(index,row){
      this.checkbox=[]
      if(row.isnew===1){
        this.checkbox.push("新车")
      }
      if(row.rushsale===1){
        this.checkbox.push("急售")
      }
      if(row.transitivecountry===1){
        this.checkbox.push("可迁全国")
      }
      if(row.costeffective===1){
        this.checkbox.push("超值")
      }
      if(row.quasinewcar===1){
        this.checkbox.push("准新车")
      }
    },
    /**
     * 监听变化
     */
    checkboxChange(){
      if(this.checkbox.includes("新车")){
        this.carForm.isnew = 1;
      } else {
        this.carForm.isnew = 0;
      }
      if(this.checkbox.includes("超值")){
        this.carForm.costeffective = 1;
      } else {
        this.carForm.costeffective = 0;
      }
      if(this.checkbox.includes("急售")){
        this.carForm.rushsale = 1;
      } else {
        this.carForm.rushsale = 0;
      }
      if(this.checkbox.includes("可迁全国")){
        this.carForm.transitivecountry = 1;
      } else {
        this.carForm.transitivecountry = 0;
      }
      if(this.checkbox.includes("准新车")){
        this.carForm.quasinewcar = 1;
      } else {
        this.carForm.quasinewcar = 0;
      }
    },
    /**
     * 获取预览结果
     * @param index 索引
     * @param row 行数据
     */
    getCarResourceByCarId(index,row){
      this.$http.get("/carResources/carId/"+row.id).then(result=>{
        result = result.data
        if(result.success) {
          if(result.object !== null){
            this.carResource = result.object;
            this.imgFileList=[]
            this.viceImgFileList = [];
            this.moreImgFileList = []
            if(result.object.img){
              // 拆分字符串
              for (const resultElement of result.object.img.split(",")) {
                // 放入到imgFileList中 {name,url}
                this.imgFileList.push(
                    {name:this.imageUrl+resultElement,url:this.imageUrl+resultElement,response:{object:resultElement}}
                )
              }
            }
            if(result.object.viceimg){
              for (const resultElement of result.object.viceimg.split(",")) {
                // 放入到imgFileList中 {name,url}
                this.viceImgFileList.push(
                    {name:this.imageUrl+resultElement,url:this.imageUrl+resultElement,response:{object:resultElement}}
                )
              }
            }
            if(result.object.moreimg){
              for (const resultElement of result.object.moreimg.split(",")) {
                // 放入到imgFileList中 {name,url}
                this.moreImgFileList.push(
                    {name:this.imageUrl+resultElement,url:this.imageUrl+resultElement,response:{object:resultElement}}
                )
              }
            }
          }
        }
      })
    },
    /**
     * 封面回调
     * @param response
     * @param file
     * @param fileList
     */
    handleSuccess(response, file, fileList){
      this.carForm.cover = response.object;
    },
    /**
     * 资源维护主图删除
     * @param file
     * @param fileList
     */
    handleImgRemove(file, fileList){
      let filePath =file.response.object;
      this.$http.delete("/fastDfs/delete?path="+filePath).then(res=>{
            if(res.data.success){
              this.carResource.img = "";
              if(fileList && fileList.length > 0) {
                for (let i = 0; i < fileList.length; i++) {
                  this.carResource.img += fileList[i].response.object +",";
                }
                if(this.carResource.img.endsWith(",")){
                  this.carResource.img = this.carResource.img.substring(0,this.carResource.img.length-1)
                }
              }
            }
          })
    },
    /**
     * 资源维护主题成功回调
     * @param response
     * @param file
     * @param fileList
     */
    handleImgSuccess(response, file, fileList){
      if(this.carResource.img){
        this.carResource.img = this.carResource.img + "," + response.object;
      } else {
        this.carResource.img = response.object;
      }
    },
    handleViceImgRemove(file, fileList){
      let filePath =file.response.object;
      this.$http.delete("/fastDfs/delete?path="+filePath).then(res=>{
        if(res.data.success){
          this.carResource.viceimg = null;
          if(fileList && fileList.length > 0) {
            for (let i = 0; i < fileList.length; i++) {
              this.carResource.viceimg += fileList[i].response.object +",";
            }
            if(this.carResource.viceimg.endsWith(",")){
              this.carResource.viceimg = this.carResource.viceimg.substring(0,this.carResource.viceimg.length-1)
            }
          }
        }
      })
    },
    handleMoreImgRemove(file, fileList){
      console.log(file)
      let filePath =file.response.object;
      this.$http.delete("/fastDfs/delete?path="+filePath).then(res=>{
        if(res.data.success){
          this.carResource.moreimg = null;
          if(fileList && fileList.length > 0) {
            for (let i = 0; i < fileList.length; i++) {
              this.carResource.moreimg += fileList[i].response.object +",";
            }
            if(this.carResource.moreimg.endsWith(",")){
              this.carResource.moreimg = this.carResource.moreimg.substring(0,this.carResource.moreimg.length-1)
            }
          }
        }
      })
    },
    handleViceSuccess(response, file, fileList){
      if(this.carResource.viceimg){
        this.carResource.viceimg = this.carResource.viceimg + "," + response.object;
      } else {
        this.carResource.viceimg = response.object;
      }
    },
    handleMoreSuccess(response, file, fileList){
      if(this.carResource.moreimg){
        this.carResource.moreimg = this.carResource.moreimg + "," + response.object;
      } else {
        this.carResource.moreimg = response.object;
      }
    },
    /**
     * 封面删除图片
     * @param file 文件
     * @param fileList 封面文件列表
     */
    handleRemove(file, fileList){
      let filePath =file.response.object;
      this.$http.delete("/fastDfs/delete?path="+filePath)
          .then(res=>{
            if(res.data.success){
              this.$message.success("删除成功！");
              this.carForm.cover = null;
            }else{
              this.$message.success("删除失败！");
            }
          })
    },
    handlePreview(file){

    },
    search(){
      this.query.currentPage = 1;
      this.getCars();
    },
    handleCurrentChange(val) {  // val是当前页
      this.query.currentPage = val;
      this.getCars();
    },
    /**
     * 获取汽车分页数据
     */
    getCars() {
      this.listLoading = true;  // 弹出加载框
      this.$http.post("/car/carWaitAudit",this.query)   // axios.defaults.baseURL+/car  http://localhost:80/api/car
          .then(result => {
            result = result.data; // result.data  {success:true,message:"",result:{total:1,rows:[]}}
            if(result.success){
              this.pageInfo = result.object;
              this.listLoading = false;  // 关闭加载框
            }else{
              this.$message({message: '查询分页失败!'+result.message, type: 'error'});
            }
            this.listLoading = false;  // 关闭加载框
          })
          .catch(result => {
            this.$message({message: "查询分页失败!", type: 'error'});
          })
    },
    /**
     * 汽车删除
     * @param index 索引
     * @param row 行数据
     */
    handleDel: function (index, row) {
      this.$confirm('确认删除该记录吗?', '提示', {
        type: 'warning'
      }).then(() => {
        this.listLoading = true;
        this.$http.delete("/car/"+row.id)
            .then(result => {
              result = result.data;
              if(result.success){
                this.$message({message: '删除成功', type: 'success'});
                // 刷新列表
                this.query.currentPage = 1;
                this.getCars();
                this.listLoading = false;  // 关闭弹出框
              }else{
                this.$message({message: '删除失败!'+result.message, type: 'error'});
              }
            })
      }).catch(() => {
        this.$message({message: '已取消删除', type: 'info'});
      });
    },
    getCarTypeTree(){
      this.$http.get("/carType/tree")
          .then(result => {
            result = result.data; // result => {successs:true,message:"",result:[]}
            if(result.success){
              this.carTypes = result.object;
            }else{
              this.$message({message: '获取树失败!'+result.message, type: 'error'});
            }
          }).catch(result => {
        this.$message({message: '获取树失败!', type: 'error'});
      })
    },
    getEmployeeList(){
      this.$http.get("/employee")
          .then(result => {
            result = result.data;
            if(result.success){
              this.employees = result.result;
            }else{
              this.$message({message: '获取员工列表失败!'+result.message, type: 'error'});
            }
          }).catch(result => {
        this.$message({message: '获取员工列表失败!', type: 'error'});
      })
    },
    /**
     * 显示编辑界面
     * @param index 索引
     * @param row 行数据
     */
    handleEdit: function (index, row) {
      this.setCheckbox(index,row)
      this.carFormVisible = true;

      this.carForm = Object.assign({}, row);
      if(this.carForm.carDetail === null) {
        this.carForm.carDetail={
          info:"",
        }
      }
      // 商品类型 和 上架状态赋值
      this.carForm.typeId = row.type.id;
      this.carForm.state = String(this.carForm.state);
      if(this.carForm.manager == null){
        this.carForm.manager = {id:null}
      }
      if(row.path != null){
        let arrays = row.path.split("/");    // ['', '1', '2', '20'] 根据/分割之后,第一个位置是一个空字符串,是不需要的,另外最后一个值是当前部门的id,而不是父部门的id,所以也不需要
        let ids = [];
        for(let i=1;i<arrays.length-1;i++){
          ids.push(parseInt(arrays[i]))    // 数组分割之后里面的值都是字符串,而部门树的id都是数字,他们匹配不上就不能回显,因此需要parseInt()转一下
        }
        this.carForm.parent = ids;
      }

      // 获取所有的员工数据
      this.getEmployeeList();
      // 获取部门树
      this.getCarTypeTree();
    },
    /**
     * 显示新增界面
     */
    handleAdd: function () {
      this.checkbox = [];
      this.carFormVisible = true;
      this.carForm = {
        id:"",
        title:"",
        cover:"",
        saleprice:"",
        costprice:"",
        isnew:"",
        reigstertime:"",
        mileage:"",
        shop_id:"",
        shopname:"",
        createtime:"",
        manager:{
          id:""
        },
        parent:{
          id:""
        },
        path:"",
        state:"",
        carDetail: {
          info:""
        },
        auditstate:"",
        node:""
      }
      // 获取所有的员工数据
      this.getEmployeeList();
      // 获取部门树
      this.getCarTypeTree();
    },
    /**
     * 汽车资源维护保存
     */
    saveCarResource(){
      this.$confirm('确认提交吗？', '提示', {}).then(() => {
        this.carFormLoading = true;
        this.$http.put("/carResources",this.carResource)
            .then(result => {
              result = result.data;
              if(result.success){
                this.$message({message: '保存成功', type: 'success'});
                this.carFormLoading = false;
                this.resourceVisible = false;
              }else{
                this.$message({message: '保存失败!'+result.message, type: 'error'});
              }
            }).catch(result => {
          this.$message({message: '保存失败!', type: 'error'});
        })
      })
    },
    /**
     * 新增修改保存方法
     */
    save: function () {
      this.checkboxChange()
      this.$refs.carForm.validate((valid) => {
        if (valid) {
          this.$confirm('确认提交吗？', '提示', {}).then(() => {
            this.carFormLoading = true;
            let para = Object.assign({}, this.carForm);
            // 级联下拉框绑定后的值是数组,但是后端的parent需要的是一个对象,所以需要我们手动转一下
            if(para.parent != null){
              let array = para.parent;
              // 当用户选择多级部门以后,对于该部门而言,最后一个部门id才是它的父部门
              para.parent = {id:array[array.length-1]};
            }
            this.$http.post("/car/carAudit",para)
                .then(result => {
                  result = result.data;
                  if(result.success){
                    this.carFormLoading = false;
                    this.query.currentPage = 1;
                    this.getCars();
                    this.carFormVisible = false;
                  }else{
                    this.carFormVisible = false;
                  }
                }).catch(result => {
              this.$message({message: '保存失败!', type: 'error'});
            })
          });
        }
      });
    },
    selsChange: function (sels) {
      this.sels = sels;
    },
    //批量删除
    batchRemove: function () {
      var ids = this.sels.map(item => item.id).toString();
      this.$confirm('确认删除选中记录吗？', '提示', {
        type: 'warning'
      }).then(() => {
        this.listLoading = true;
        //NProgress.start();
        let para = { ids: ids };
        batchRemoveUser(para).then((res) => {
          this.listLoading = false;
          //NProgress.done();
          this.$message({
            message: '删除成功',
            type: 'success'
          });
          this.getCars();
        });
      })
    }
  },
  mounted() {
    this.getCars();  // 做分页查询
  }
}

</script>

<style scoped>

</style>